package com.dingreading.cloud.web.controller;

import com.dingreading.cloud.common.util.IpUtil;
import com.dingreading.cloud.common.util.aliyun.CdnUtil;
import com.dingreading.cloud.web.service.CdnService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.apache.commons.lang3.StringUtils;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;

@RestController
@RequestMapping("/cdn/auth")
@Api(tags = "cdn远程鉴权")
public class OssCdnAuthController {

    @Resource
    private CdnService cdnService;


    @ApiOperation(value = "阿里云验证token")
    @GetMapping(value = "/check")
    public ResponseEntity<String> check(
            HttpServletRequest request
    ) throws Exception {
//        System.out.println("cdn远程鉴权方式");

        // 获取token
        String token = request.getParameter("token");
        if (StringUtils.isBlank(token)) {
            return ResponseEntity.status(403).body("Invalid token");
        }

        // 获取ip
        String ip = IpUtil.getIpAddr(request);
//        System.out.println("ip = " + ip);
        String remoteAddr = request.getParameter("remote_addr");
//        System.out.println("remote_addr = " + remoteAddr);
        if (StringUtils.isBlank(ip) || StringUtils.isBlank(remoteAddr)) {
            return ResponseEntity.status(403).body("Invalid ip");
        }

        // 获取文件访问地址
        String uri = request.getParameter("uri");
//        System.out.println("uri = " + uri);
        if (StringUtils.isBlank(uri)) {
            return ResponseEntity.status(403).body("Invalid uri");
        }

        // 获取referer
        String httpReferer = request.getParameter("http_referer");
//        System.out.println("http_referer = " + httpReferer);
        // 防跨域
        if (StringUtils.isBlank(httpReferer) || (!httpReferer.contains(CdnUtil.PROD_REFERER) && !httpReferer.contains(CdnUtil.TEST_REFERER)) && !httpReferer.contains(CdnUtil.SCS_REFERER)) {
            return ResponseEntity.status(403).body("Invalid httpReferer");
        }

        // token鉴权逻辑
        boolean isAuthValid = cdnService.validateToken(token, ip, remoteAddr, uri, httpReferer);
//        System.out.println("isAuthValid = " + isAuthValid);
        if (isAuthValid) {
            // 鉴权通过！返回200状态码
            return ResponseEntity.ok().body("Auth Success");
        } else {
            // 鉴权失败，返回403状态码（CDN会将此结果返回给用户）
            return ResponseEntity.status(403).body("Access Denied");
        }
    }

}